package de.koller.aframe.util.thread;

import de.koller.oceanFramework.thread.buffer.Buffer;

public class ThreadRootHandle implements Runnable {
	private final Thread thread;
	
	private boolean running = false;
	private final Buffer<ICommand> commands = new Buffer<>();
	private ILoopHandler loopHandler = new DefaultLoopHandle();
	
	public ThreadRootHandle( String threadname ) {
		thread = new Thread( this, threadname );
	}

	public synchronized void start() {
		running = true;
		thread.start();
	}
	
	@Override
	public void run() {
		while( running )
			loopHandler.loopHandle();
	}
	
	public void call( ICommand command ) {
		commands.push( command );
	}
	
	public ICommand pop() {
		return commands.pop();
	}
	
	public void stop() {
		running = false;
		call( new PseudoCommand() );
	}

	public Thread getThread() {
		return thread;
	}

	public void setLoopHandler( ILoopHandler loopHandler ) {
		this.loopHandler = loopHandler;
	}

	public boolean hasCommands() {
		return !commands.isEmpty();
	}
	
	private class DefaultLoopHandle implements ILoopHandler {

		@Override
		public void loopHandle() {
			ICommand cmd = commands.pop();
			cmd.handle();
		}
		
	}
	
}
